package com.example.My.service.Impl;

import com.example.My.pojo.Mail;
import com.example.My.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: 谢宇
 * CreatTime 2023/11/18 11:46
 * Version 1.0.0
 */
@Service
public class MailServiceImpl implements MailService {


    //注入邮件工具类
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private Configuration configuration;

    @Value("${spring.mail.username}")
    private String sendMailer;

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    //检查邮件内容
    public void checkMail(Mail mailRequest) {
        Assert.notNull(mailRequest,"邮件请求不能为空");
        Assert.notNull(mailRequest.getSendTo(), "邮件收件人不能为空");
        Assert.notNull(mailRequest.getSubject(), "邮件主题不能为空");
        Assert.notNull(mailRequest.getText(), "邮件收件人不能为空");
    }

    @Override
    public void sendSimpleMail(Mail mailRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        checkMail(mailRequest);
        //邮件发件人
        message.setFrom(sendMailer);
        //邮件收件人 1或多个
        message.setTo(mailRequest.getSendTo().split(","));
        //邮件主题
        message.setSubject(mailRequest.getSubject());
        //邮件内容
        message.setText(mailRequest.getText());
        //邮件发送时间
        message.setSentDate(new Date());
        javaMailSender.send(message);
        logger.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
    }


    /**
     * 发送freeMaker模板邮件
     * @param mailRequest
     */
    @Override
    public void sendHtmlMail(Mail mailRequest) {
        checkMail(mailRequest);
        try {
            // 定义个数据根节点
            Map<String,Object> root = new HashMap<>();
            // 往里面塞第一层节点
            root.put("username",mailRequest.getUser());
            root.put("code",mailRequest.getCode());
            Template template = configuration.getTemplate("mail.ftl");
            String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, root);
            System.out.println("--->"+s);

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            /** 设置邮件重要性级别 */
            mimeMessage.setHeader("Importance","High");
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(this.sendMailer,"验证码");
            helper.setTo(mailRequest.getSendTo());
            helper.setSubject(mailRequest.getSubject());
            // todo 这里的s是使用了freeMaker的结果
            helper.setText(s,true);
            javaMailSender.send(mimeMessage);
            logger.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
        } catch (MessagingException | IOException |TemplateException e) {
            logger.error("发送邮件时发生异常！",e);
        }
    }
}
